﻿using eProcurement.BLL;
using eProcurement.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace eProcurement.members
{
    /// <summary>
    /// Summary description for FileHandler
    /// </summary>
    public class FileHandler : IHttpHandler
    {

        public void ProcessRequest( HttpContext context )
        {
            Manager manager = new Manager();

            if ( context.Request[ "file" ] != null && context.Request[ "pid" ] != null )
            {
                Project project = manager.GetProject( Convert.ToInt32( context.Request[ "pid" ] ) );

                byte[] Content = project.ScopeDocument;
                string filename = "";

                if ( context.Request[ "file" ] == "scope" )
                {
                    Content = project.ScopeDocument;
                    filename = project.ScopeFileName;
                }
                else if ( context.Request[ "file" ] == "supporting" )
                {
                    Content = project.AdditionalDocument;
                    filename = project.AdditionalDocsName;
                }
                
                context.Response.ContentType = "text/plain";
                context.Response.AddHeader( "content-disposition", "attachment; filename=" + filename );
                context.Response.BufferOutput = true;
                context.Response.OutputStream.Write( Content, 0, Content.Length );
                context.Response.End();
            }
            else if ( context.Request[ "file" ] != null && context.Request[ "sup" ] != null )
            {
                Supplier supplier = (Supplier)manager.GetAppUser( Guid.Parse( context.Request[ "sup" ] ) );
                byte[] Content = supplier.Bids.FirstOrDefault().Documents;
                string filename = supplier.Bids.FirstOrDefault().Filename;

                context.Response.ContentType = "text/plain";
                context.Response.AddHeader( "content-disposition", "attachment; filename=" + filename );
                context.Response.BufferOutput = true;
                context.Response.OutputStream.Write( Content, 0, Content.Length );
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}